package by.koleda.photoupdater.manager;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.ContactsContract;
import by.koleda.photoupdater.helpers.ContextHolder;

public class ContactsManager {
	
	private static Context context = ContextHolder.getInstance().getContext();
	
	public final static String KEY_ID = "_ID";
	public final static String KEY_DISPLAY_NAME = "DISPLAY_NAME";
	
	public static ArrayList<HashMap<String, String>> getContacts() {
		
		ArrayList<HashMap<String, String>> contactsList = new ArrayList<HashMap<String, String>>();
		
		String[] projection = {
				ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME,
		};
		
		Context context = ContextHolder.getInstance().getContext();
		Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
		
		int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
		int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
		
		while(cursor.moveToNext())
		{
			String name = cursor.getString(nameIdx);
			String id = cursor.getString(idIdx);
			HashMap<String, String> result = new HashMap<String, String>();
			result.put(KEY_ID, id);
			result.put(KEY_DISPLAY_NAME, name);
			contactsList.add(result);
		}
		
		cursor.close();
		
		return contactsList;
	}

	
	public static Bitmap getContactPhoto(String id) {
        Bitmap photo = null;
        Long i = Long.parseLong(id);
        
        try {
            InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
            		ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, i));

            if (inputStream != null) {
                photo = BitmapFactory.decodeStream(inputStream);
                
            }

            if (inputStream != null) {
            	inputStream.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return photo;
	}
}